import { HashService } from '@app/hash';
import { PrismaService } from '@app/prisma';
import { DepartmentEntity } from '@app/prisma/department.entity/department.entity';
import { ForbiddenError } from '@nestjs/apollo';
import { UseGuards } from '@nestjs/common';
import { Args, Int, Mutation, Resolver } from '@nestjs/graphql';
import { AccountPower, GqlAuthPowerGuard } from 'src/auth/auth.guard';

@Resolver()
export class DepartmentResolver {
    constructor(
        private readonly prisma: PrismaService,
        private readonly hashService: HashService
    ) { }

    @Mutation(() => DepartmentEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    async addDepartment(
        @Args("collegeId", { type: () => Int }) collegeId: number,
        @Args("name") name: string
    ) {
        const college = await this.prisma.college.findUnique({ where: { id: collegeId } })
        if (!college) throw new ForbiddenError("404")
        return await this.prisma.department.create({
            data: {
                name,
                college: {
                    connect: {
                        id: college.id
                    }
                },
                hash: this.hashService.cryptoIdAndName(
                    collegeId,
                    name
                )
            }
        })
    }

    @Mutation(() => DepartmentEntity)
    @UseGuards(new GqlAuthPowerGuard(AccountPower))
    async updDepartment(
        @Args("id", { type: () => Int }) id: number,
        @Args("collegeId", { type: () => Int }) collegeId: number,
        @Args("name") name: string
    ) {
        const college = await this.prisma.college.findUnique({ where: { id: collegeId } })
        if (!college) throw new ForbiddenError("404")
        return await this.prisma.department.update({
            where: {
                id
            },
            data: {
                name,
                college: {
                    connect: {
                        id: college.id
                    }
                },
                hash: this.hashService.cryptoIdAndName(
                    college.id,
                    name
                )
            }
        })
    }
}
